import { Injectable } from '@nestjs/common';
import OSS from 'ali-oss'; // 修改此处导入方式
import { v4 as uuidv4 } from 'uuid';

interface OSSConfig {
  accessKeyId: string;
  accessKeySecret: string;
  region: string;
  bucket: string;
}

@Injectable()
export class OSSService {
  private client: OSS;
  private bucket: string;

  constructor(config: OSSConfig) {
    this.client = new OSS(config);
    this.bucket = config.bucket;
  }

  /**
   * 上传图片到阿里云 OSS
   * @param file 图片文件
   * @param originalname
   * @param folder 存储文件夹
   * @returns 图片访问 URL
   */
  async uploadImage(file: Buffer, originalname: string, folder: string = 'images'): Promise<string> {
    try {
      // 获取文件扩展名
      const ext = originalname.split('.').pop();

      // 生成唯一文件名，避免冲突
      const fileName = `${folder}/${uuidv4()}.${ext}`;

      // 上传文件到 OSS
      const result = await this.client.put(fileName, file);

      // 获取默认的OSS URL
      let url = result.url;

      // 将默认域名替换为自定义域名
      if (url) {
        url = url.replace('http://helper-oss.oss-cn-beijing.aliyuncs.com', 'https://oss.zyhxai.com');
      }
      // 返回文件访问 URL
      return url;
    } catch (error) {
      console.error('OSS 图片上传失败:', error);
      throw new Error('图片上传失败，请稍后重试');
    }
  }

  /**
   * 从 OSS 删除图片
   * @param url 图片 URL
   */
  async deleteImage(url: string): Promise<void> {
    try {
      // 从 URL 中提取文件路径
      const urlObj = new URL(url);
      const objectPath = urlObj.pathname.substring(1); // 去除开头的 '/'

      await this.client.delete(objectPath);
    } catch (error) {
      console.error('OSS 图片删除失败:', error);
      throw new Error('图片删除失败，请稍后重试');
    }
  }
}
